#!/usr/bin/python
# -*- coding: utf-8 -*-
""""""
import Image, ImageDraw, ImageFont, md5, random,cStringIO,datetime,ImageColor,os,string
from jiaju.common.django.http import HttpResponse
from jiaju.business import user_manager, page_manager, privilege_manager,type_manager, article_manager
from jiaju.web.render import render_to_response
from django.http import HttpResponseRedirect
from jiaju.common.decorators import privilege_required
from jiaju.common.constants import privilege_constant
from jiaju.common.constants.constant import Constant
from jiaju.common import cache
from jiaju.business.util import FileUpload
from jiaju.model import Article

SESSION_KEY = Constant.SESSION_KEY
#@privilege_required(page_id=1, operator_id=privilege_constant.Privileges.ACTION_TYPE_VIEW)
def index(request):
    return render_to_response(request, "index.html",locals())

#@privilege_required(page_id=1, operator_id=privilege_constant.Privileges.ACTION_TYPE_VIEW)
def user_list(request):
    """用户列表"""
    page = request.REQUEST.get("page", 1)
    pagesize = request.REQUEST.get("pagesize", 10)
    uid = request.REQUEST.get("uid", None)
    total, infos = user_manager.get_user_list(page, pagesize, uid)
    return render_to_response(request, 'admin/ulist.html', locals())

#@privilege_required(page_id=2, operator_id=privilege_constant.Privileges.ACTION_TYPE_VIEW)
def page_list(request):
    """页面权限名称列表"""
    page = request.REQUEST.get("page", 1);
    pagesize = request.REQUEST.get("pagesize", 10)
    total , infos = page_manager.get_page_info(page, pagesize);
    return render_to_response(request, 'admin/plist.html', locals())

def type_list(request):
    """类型列表"""
    parent_type = type_manager.get_type_list()
    son_type = type_manager.get_type_list(pid = 0)
    return render_to_response(request, 'admin/typelist.html', locals())

def article_list(request):
    """文章列表页"""
    page = int(request.REQUEST.get("page",1))
    pagesize = int(request.REQUEST.get("pagesize",20))
    total,articles = article_manager.get_article_list(page, pagesize)
    return render_to_response(request, 'admin/articlelist.html', locals())

def article_info(request):
    """文章详细内容"""
    id = request.REQUEST.get("id",None)
    if id is None or id == "":
        code = "参数错误"
        return render_to_response(request, 'admin/no_privilege.html', locals())
    articleinfo = article_manager.get_article_one(id)
    imgcontent = str(articleinfo.imgcontent)
    imgcontent_split = None
    if imgcontent != "None":
        imgcontent_split = imgcontent.split(",")
    return render_to_response(request, 'admin/articleinfo.html', locals()) 

def pic_add(request):
    """图片添加"""
    id = request.REQUEST.get("id",None)
    if id is None:
        response = HttpResponseRedirect("/admin/article_info/?id=%s&tip=%s"%(id,"上传失败"))
        return response
    article = Article().load(id=id)
    if article is None:
        response = HttpResponseRedirect("/admin/article_info/?id=%s&tip=%s"%(id,"上传失败"))
        return response
    else:
        code,file_name = FileUpload.addPic(request,id)
        imgcontent = ''
        if article.imgcontent is not None:
            imgcontent = article.imgcontent
        if code == 1:
            if imgcontent == '' :
                article.imgcontent = "%s"%(file_name)
            else:
                article.imgcontent = "%s,%s"%(imgcontent,file_name)
            article.persist()
        response = HttpResponseRedirect("/admin/article_info/?id=%s"%id)
        return response
    
def article_add(request):
    """文章修改添加"""
    id = request.REQUEST.get("id",None)
    title = request.REQUEST.get("title","")
    created_time = request.REQUEST.get("created_time","")
    froms = request.REQUEST.get("froms","")
    from_url = request.REQUEST.get("from_url","")
    author = request.REQUEST.get("author","")
    digest = request.REQUEST.get("digest","") 
    content = request.REQUEST.get("content","")
    
    if id :
        """修改"""
        article = Article()
        article.id = id
        article.title = title
        article.created_time = created_time
        article.froms = froms
        article.from_url = from_url
        article.author = author
        article.digest = digest
        article.content = content
        article.persist()
        response = HttpResponseRedirect("/admin/article_list/")
        return response
    else:
        '''添加'''
        

def logout(request):
    return user_manager.logout(request)
    
def login(request):
    request_user = user_manager.get_userinfo(request)
    if request_user is not None:
        response = HttpResponseRedirect('/admin/index/')
        response.set_cookie(SESSION_KEY,request_user.session_id)
        return response
    user_id = request.REQUEST.get("user_id")
    passwd = request.REQUEST.get("passwd")
    if user_id and passwd :
        code,session_id = user_manager.login(request,user_id,passwd)
        if code == 0:
            response = HttpResponseRedirect('/admin/index/')
            response.set_cookie(SESSION_KEY,session_id)
            return response
    return render_to_response(request, "admin/login.html", locals());

#@privilege_required(page_id=4, operator_id=privilege_constant.Privileges.ACTION_TYPE_VIEW)
def privilege(request):
    """用户权限列表"""
    page = request.REQUEST.get("page", 1)
    user_id = request.REQUEST.get("id", 0);
    infos = []
    temps = []
    if user_id:
        total, temps = page_manager.get_page_info(1, 100)
    else:
        raise "uid is 0 ... "
    for info in temps:
        privileges = privilege_manager.get_privilege_list(user_id , info.id)
        if privileges :
            info.privilege_value = privileges.privilege_value
        infos.append(info)
    return render_to_response(request, 'admin/prlist.html', locals())

def noprivilege(request):
    return render_to_response(request, 'admin/no_privilege.html', locals())

def get_check_code_image(request,image='media/images/checkcode.gif'):    
    import Image, ImageDraw, ImageFont, random    
    color = ImageColor.getrgb('black')
    im = Image.new('RGB',(160,60), color)    
    draw = ImageDraw.Draw(im)    
    mp = md5.new()    
    mp_src = mp.update(str(datetime.datetime.now()))
    mp_src = mp.hexdigest()    
    rand_str = mp_src[0:4]
    font_type = "/usr/share/fonts/bitstream-vera/VeraSe.ttf"
    if os.name == 'nt':
        font_type = 'C:\\Windows\\Fonts\\arial.ttf'
    draw.text((10,10), rand_str[0], font=ImageFont.truetype(font_type, random.randrange(25,50)))    
    draw.text((48,10), rand_str[1], font=ImageFont.truetype(font_type, random.randrange(25,50)))    
    draw.text((85,10), rand_str[2], font=ImageFont.truetype(font_type, random.randrange(25,50)))    
    draw.text((120,10), rand_str[3], font=ImageFont.truetype(font_type, random.randrange(25,50)))    
    del draw
    """生成验证码key,设置到cookies"""
    checkkey = random.randrange(0,10000000)
    buf = cStringIO.StringIO()    
    im.save(buf, 'gif')
    response = HttpResponse(buf.getvalue(),'image/gif')
    response.set_cookie("checkcode", checkkey)
    
    cache.set(checkkey, rand_str, 600)
    return response
